using System;
using System.Collections.Generic;
using System.Xml;
using System.Collections.ObjectModel;

namespace planning
{
	public class Semaine : ObservableObject
	{
		// ----- ATTRIBUTS -----
		private int numero;
		private ICollection<Jour> jours = new ObservableCollection<Jour>();

		// ----- CONSTRUCTEURS -----
		public Semaine()
		{
			// Start of user code for default constructor
			// End of user code for default constructor
		}

		// ----- ACCESSEURS -----
		public int Numero
		{
			get { return numero; }
			set { numero = value; ObjectChanged("numero"); }
		}

		public ICollection<Jour> Jours
		{
			get { return jours; }
			set { jours = value; ObjectChanged("jours"); }
		}


		private static Dictionary<string, Semaine> references = new Dictionary<string, Semaine>();

		public static Semaine fromXml(XmlNode node)
		{
			Semaine semaine;
			XmlNode refAttribute = node.SelectSingleNode("@ref");
			XmlNode idAttribute = node.SelectSingleNode("@id");

			if(refAttribute != null) {
				if(references.ContainsKey(refAttribute.Value)) {
					return references[refAttribute.Value];
				} else {
					semaine = new Semaine();
					references.Add(refAttribute.Value, semaine);
					return semaine;
				}
			}

			if(idAttribute != null && references.ContainsKey(idAttribute.Value)) {
				semaine = references[idAttribute.Value];
			} else {
				semaine = new Semaine();

				if(idAttribute != null) {
					references.Add(idAttribute.Value, semaine);
				}
			}

			if(node.SelectSingleNode("@numero") != null)
				semaine.Numero = Convert.ToInt32(node.SelectSingleNode("@numero").Value);

			foreach (XmlNode subElement in node.SelectNodes("jours/*"))
			{
				Jour subObject = Jour.fromXml(subElement);
				semaine.Jours.Add(subObject);
			}

			

			return semaine;

		}

		public virtual XmlElement toXml(XmlDocument document)
		{
			// Start of user code for toXml
            XmlElement element = document.CreateElement("Semaine");
            XmlAttribute numeroAttribute = document.CreateAttribute("numero");
            numeroAttribute.Value = Numero.ToString();
            element.Attributes.Append(numeroAttribute);

            XmlElement joursElement = document.CreateElement("jours");
            element.AppendChild(joursElement);
            foreach (Jour subObject in Jours)
            {
                joursElement.AppendChild(subObject.toXml(document));
            }

            return element;
			// End of user code for toXml
		}


	}

}
